import dagre from 'dagre';
import type { FlowNode, FlowEdge } from '@/models/jdf';
import type { DagreRankdir } from '@/models/settings';

/**
 * Applies layout using Dagre. (Original Version for JDF Model)
 * Filters hidden nodes/edges *before* layout calculation.
 *
 * @param allNodes All flow nodes (JDF Model).
 * @param allEdges All flow edges (JDF Model).
 * @param rankdir Layout direction ('TB' or 'LR').
 * @returns An object with the *layouted* visible nodes and edges.
 */
export function applyDagreLayout(
    allNodes: FlowNode[], // Use FlowNode
    allEdges: FlowEdge[], // Use FlowEdge
    rankdir: DagreRankdir = 'TB'
): { nodes: FlowNode[]; edges: FlowEdge[] } { // Return OLD types

    // Filter out hidden elements BEFORE layout
    const visibleNodes = allNodes.filter(n => !n.hidden);
    // Assuming old FlowEdge had hidden property, adjust if necessary
    const visibleEdges = allEdges.filter(e => !e.hidden);
    const visibleNodeIds = new Set(visibleNodes.map(n => n.id));

    // Ensure edges only connect visible nodes
    const layoutEdges = visibleEdges.filter(e =>
        visibleNodeIds.has(e.source) && visibleNodeIds.has(e.target)
    );

    if (visibleNodes.length === 0) {
        return { nodes: [], edges: [] };
    }

    const dagreGraph = new dagre.graphlib.Graph();
    dagreGraph.setDefaultEdgeLabel(() => ({}));
    // Use HARDCODED spacing for the original function
    dagreGraph.setGraph({ rankdir: rankdir, nodesep: 80, ranksep: 100 });

    const nodeWidth = 216;
    const nodeHeight = 80;

    visibleNodes.forEach(node => {
        dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
    });

    layoutEdges.forEach(edge => {
        dagreGraph.setEdge(edge.source, edge.target);
    });

    try {
        dagre.layout(dagreGraph);
    } catch (layoutError: any) {
        console.error("[DagreLayout Original] Layout calculation failed:", layoutError);
        return { nodes: visibleNodes, edges: layoutEdges };
    }

    visibleNodes.forEach(node => {
        const dagreNode = dagreGraph.node(node.id);
        if (dagreNode) {
            node.position = {
                x: dagreNode.x - dagreNode.width / 2,
                y: dagreNode.y - dagreNode.height / 2
            };
        } else {
            console.warn(`[DagreLayout Original] Node ${node.id} not found in Dagre graph after layout.`);
        }
    });

    return { nodes: visibleNodes, edges: layoutEdges };
} 